package cn.xueden.util;

import cn.xueden.security.SysUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;

/**
 * @author:梁志杰
 * @date:2025/6/8
 * @description:cn.xueden.util
 * @version:1.0
 */
@Slf4j
public class SecurityUtil {

    public SecurityUtil() {
    }

    /**
     * 获取当前登录用户的ID
     */
    public static Integer getUserId() {
        try {
            var context = SecurityContextHolder.getContext();
            if (context == null){
                return null;
            }
            var authentication = context.getAuthentication();
            if (authentication == null){
                return null;
            }
            Object  principal = authentication.getPrincipal();
            if (!(principal instanceof SysUserDetails)){
                return null;
            }
            SysUserDetails  user = (SysUserDetails) principal;
            if (user.getUser() == null||  user.getUser().getId() == null){
                return null;
            }
            return user.getUser().getId();
        } catch (Exception e) {
            log.error("获取当前登录用户信息失败",e);
            return null;
        }
    }

    /**
     * 获取当前用户角色
     * @return 角色
     */
    public static String getRole(){
        List<? extends GrantedAuthority> list = SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream().toList();
        return list.get(0).toString();
    }
}
